/*  FIXME : 拖拽任意放置，拖拽排序；编辑不可添加值，实现预览（不保存添加值），重置按钮导致验证规则变化，
  TODO: 新增其他属性
*/
import { computed, defineComponent, provide, reactive, ref } from "vue";
import "./editor.scss";
import deepcopy from "deepcopy";
import EditorPropsSet from "./jsx/editor-props-set.jsx";
import Preview from "./preview.jsx";
import axios from "axios";
axios.defaults.baseURL = "http://182.151.11.69:31011";

export default defineComponent({
  props: {
    modelValue: Object, // mockData `{container:"",blocks:[]}`
  },
  emits: ["update:modelValue", "closeEditor"],
  setup(props, ctx) {
    const data = computed({
      get() {
        return props.modelValue;
      },
      set(value) {
        ctx.emit("update:modelValue", deepcopy(value));
      },
    });
    // console.log(666, data.value);

    let lastCheckItem = null;
    let dragItem = null;

    //拖拽
    const onDragstart = (e, item) => {
      // console.log(123, e);
      dragItem = deepcopy(item);
    };

    const onDragover = (e) => {
      e.preventDefault();
    };

    const onDrop = (e) => {
      // console.log(45556, e, dragItem);
      dragItem.keyName = Math.random().toString(36).substr(2); //赋值随机数
      dragItem.propName = "";
      data.value.blocks.push(dragItem);
    };

    //配置文件
    //  属性配置
    function createText(label, valid, types) {
      return {
        type: "input",
        valid,
        types,
        label,
      };
    }
    function createSelect(label, valid, options) {
      return {
        type: "select",
        valid,
        label,
        options,
      };
    }
    const configList = [
      {
        label: "单行输入",
        key: "input",
        render: (props) => <ElInput></ElInput>,
        props: {
          label: createText("名称", [
            {
              required: true,
              message: "请输入label",
              trigger: "blur",
            },
          ]),
          placeholder: createText("提示"),
          propName: createText("属性名", [
            {
              required: true,
              message: "请输入propName",
              trigger: "blur",
            },
          ]),
          mustFill: createSelect(
            "必填",
            [
              {
                required: true,
                message: "请选择必填",
                trigger: "change",
              },
            ],
            [
              { label: "必填", value: true },
              { label: "非必填", value: false },
            ]
          ),
          validata: createText(
            "验证规则",
            [
              {
                required: true,
                message: "请输入验证规则",
                trigger: "blur",
              },
            ],
            "textarea"
          ),
          // keyName: Math.random().toString(36).substr(2),
          // validate: [
          //   // {
          //   //   required: true,
          //   //   message: "请输入intput类型",
          //   //   trigger: "blur",
          //   // },
          // ],
        }
      },
      {
        label: "下拉选择器",
        key: "select",
        render: (props) => <ElInput></ElInput>,
        props: {
          options: [
            { label: "左对齐", value: "left" },
            { label: "右对齐", value: "right" },
          ],
        }
      },
    ];
    provide("configList", configList);
    const configMap = [];
    configList.forEach((item) => {
      configMap[item.key] = item;
    });

    //formItem选中
    const onMouseenter = (e) => {
      // console.log(1233333,e);
    };
    const onMousedown = (e, item) => {
      // console.log(4444,e);
      clearFocus();
      e.stopPropagation();
      item.focus = true;
      lastCheckItem = deepcopy(item);
    };
    const clearFocus = () => {
      lastCheckItem = null;
      data.value.blocks.forEach((item) => {
        item.focus = false;
      });
    };

    //改变data的值
    const changeItem = (newItem) => {
      //替换data.value['blocks']中keyName 等于newItem.keyName的item
      data.value.blocks.forEach((item, index) => {
        if (item.keyName === newItem.keyName) {
          data.value.blocks[index] = newItem;
        }
      });
    };

    //提交
    const onSubmit = () => {
      console.log(123, JSON.stringify(data.value));
      ElMessageBox.confirm("是否提交" + JSON.stringify(data.value), "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let fieldsData = data.value.blocks.map((item, index) => {
          return {
            fieldName: item.propName,
            fieldType: "varchar",
            fieldLength: 100,
            need: item.mustFill ? true : false,
            notes: item.label,
            decimalPoint: 0,
            orderNum: index + 1,
          };
        });
        axios
          .post("/v1/demo/lowCode/designTable", {
            tableId: data.value.tableId,
            fields: fieldsData,
            styleJson: JSON.stringify(data.value),
          })
          .then((res) => {
            ElMessage({
              type: "success",
              message: "提交成功",
            });
            ctx.emit("closeEditor", null);
          })
          .catch((err) => {});
      });
    };

    const onInput = () => {
      ElMessageBox.prompt("请输入本平台生成的JSON字符串", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        inputErrorMessage: "Invalid Email",
      })
        .then(({ value }) => {
          ElMessage({
            type: "success",
            message: `导入成功`,
          });
          data.value = JSON.parse(value);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "请检查JSON格式",
          });
        });
    };

    const onClose = () => {
      ElMessageBox.confirm("是否关闭", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        ctx.emit("closeEditor", null);
      });
    };

    // 创建一个ref来管理对话框的显示状态
    let showPreview = ref(false);

    const onPreview = () => {
      //渲染一个 <ElDialog>,dialog内容是 <Preview>
      for (let item of data.value.blocks) {
        if (!item.propName) {
          ElMessage({
            type: "error",
            message: `请输入${item.label}propName`,
          });
          return;
        }
      }
      showPreview.value = true; // 打开对话框
    };

    const formData = reactive({
      model: {},
    });

    // 反显dom
    return () => (
      <>
        {showPreview.value && (
          <ElDialog
            beforeClose={() => {
              showPreview.value = false;
            }}
            v-model={showPreview.value}
            title="预览"
            width="50%"
          >
            <Preview
              v-model={data.value}
              isPreview={true}
              onClosePreview={() => {
                showPreview.value = false;
              }}
            ></Preview>
          </ElDialog>
        )}

        <div className="editors">
          <div className="editors-left">
            <>
              {configList.map((item) => (
                <el-button
                  draggable
                  onDragstart={(e) => onDragstart(e, item)}
                  className="editors-left-item"
                >
                  {item.label}
                </el-button>
              ))}
            </>
          </div>
          <div className="editors-center">
            <div className="editors-center-top">
              <>
                <el-button onClick={onSubmit} type="primary">
                  提交
                </el-button>
                <el-button onClick={onInput}>导入</el-button>
                <el-button onClick={onClose}>关闭</el-button>
                <el-button type="primary" onClick={onPreview}>
                  预览
                </el-button>
              </>
            </div>
            <div
              onDragover={onDragover}
              onDrop={onDrop}
              onMousedown={clearFocus}
              className="editors-center-formarea"
            >
              <ElForm
                labelPosition={data.value.container.labelPosition || "top"}
              >
                {data.value.blocks.map((block) => {
                  return (
                    <ElFormItem
                      onMouseenter={(e) => {
                        onMouseenter(e);
                      }}
                      onMousedown={(e) => onMousedown(e, block)}
                      style={
                        block.focus
                          ? { border: "2px dashed var(--el-color-primary)" }
                          : ""
                      }
                      label={block.label}
                    >
                      {{
                        input: () => (
                          <ElInput
                            v-model={formData.model[block.propName]}
                            placeholder={block.placeholder || "默认提示"}
                          ></ElInput>
                        ),
                        select: () => (
                          <ElSelect v-model={formData.model[block.propName]}>
                            <ElOption label="左对齐" value="left"></ElOption>
                            <ElOption label="顶部对齐" value="top"></ElOption>
                          </ElSelect>
                        ),
                      }[block.key]()}
                    </ElFormItem>
                  );
                })}
              </ElForm>
            </div>
          </div>
          <div className="editors-right">
            {/* 部分参数添加必填校验 */}
            <EditorPropsSet
              item={lastCheckItem}
              modelValue={data}
              onChangeItem={changeItem}
            />
          </div>
        </div>
      </>
    );
  },
});
